package com.javaxiaobear.base.common.utils.http;

import com.javaxiaobear.base.common.utils.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import lombok.extern.slf4j.Slf4j;

/**
 * 通用http发送方法
 *
 * @author javaxiaobear
 */
@Slf4j
public class HttpUtils {

  /**
   * 向指定 URL 发送GET方法的请求
   *
   * @param url 发送请求的 URL
   * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
   * @param contentType 编码类型
   * @return 所代表远程资源的响应结果
   */
  public static String sendGet(String url, String param, String contentType) {
    StringBuilder result = new StringBuilder();
    BufferedReader in = null;
    try {
      String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
      log.info("sendGet - {}", urlNameString);
      URL realUrl = new URL(urlNameString);
      URLConnection connection = realUrl.openConnection();
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep-Alive");
      connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
      connection.connect();
      in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
      String line;
      while ((line = in.readLine()) != null) {
        result.append(line);
      }
      log.info("recv - {}", result);
    } catch (ConnectException e) {
      log.error("调用HttpUtils.sendGet ConnectException, url={},param={}", url, param, e);
    } catch (SocketTimeoutException e) {
      log.error("调用HttpUtils.sendGet SocketTimeoutException, url={},param={}", url, param, e);
    } catch (IOException e) {
      log.error("调用HttpUtils.sendGet IOException, url={},param={}", url, param, e);
    } catch (Exception e) {
      log.error("调用HttpsUtil.sendGet Exception, url={},param={}", url, param, e);
    } finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        log.error("调用in.close Exception, url={},param={}", url, param, ex);
      }
    }
    return result.toString();
  }
}
